# _*_ encoding:utf-8 _*_
import matplotlib.pyplot as plt
from distance_distribution import load_edges
import math


def parse_line(line):
    elems = line.strip().split(',')
    return [int(elems[0]), elems[1], float(elems[2])]


def load_period_speed(filename, edges):
    with open(filename, "rb") as f:
        buf = []
        for line in f:
            elems = parse_line(line)
            if len(buf) == 0 or buf[0][0] == elems[0]:
                buf.append(elems)
            else:
                plot_traffic_status(edges, buf)
                del buf
                buf = list()
                buf.append(elems)
        if len(buf) != 0:
            plot_traffic_status(edges, buf)
            del buf


def plot_traffic_status(edges, velocity):
    current_time = velocity[0][0]
    v_dict = {}
    for item in velocity:
        v_dict.setdefault(item[1], item[2])

    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])
    for e_id, value in edges.items():
        X = []
        Y = []
        for point in value['shape']:
            X.append(point[0])
            Y.append(point[1])
        color = "#458b00"
        if e_id in v_dict:
            speed = value['speed']
            v = v_dict[e_id]
            if v <= speed * 0.20:
                color = "#ee2c2c"
            elif v <= speed * 0.40:
                color = "#ee7600"
            elif v <= speed * 0.6:
                color = "#eeee00"
            elif v <= speed * 0.8:
                color = '#66cd00'
            else:
                color = "#458b00"
        ax.plot(X, Y, color=color)
    hour = current_time / 3600
    minute = (current_time - hour * 3600) / 60
    time_str = "%02d:%02d" % (hour, minute)
    ax.set_title(time_str)
    # plt.show(fig)
    # plt.savefig("../../data/1025/{0}.png".format(time_str))
    # plt.savefig(fig)
    # plt.draw()
    # plt.show(fig)
    # print "filename {0}".format(time_str)
    filename = "{0}-{1}".format(hour, minute)
    # fig.savefig("../../data/1025/{0}.png".format(time_str), bbox_inches="tight")
    plt.savefig("../../data/1117/fig/{0}.png".format(filename), bbox_inches="tight")
    plt.close(fig)


def load_capacity(filename):
    capacity = {}
    with open(filename, "rb") as f:
        for line in f:
            elems = line.strip().split(',')
            road = elems[0]
            t = int(elems[1])
            come = int(elems[2])
            current = int(elems[3])
            out = int(elems[4])
            capacity.setdefault(road, {})
            capacity[road].setdefault(t, [come, current, out])
    return capacity


def plot_road_capacity(edges, capacity, filename):
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    for road, value in edges.items():
        X = []
        Y = []
        for point in value['shape']:
            X.append(point[0])
            Y.append(point[1])
        number = 0
        if road in capacity:
            number = capacity[road][1]
        max_cap = int(math.floor((value['length'] / 6.5)))
        color = '#00EE00'
        if number <= max_cap * 0.2:
            color = '#00EE00'
        elif number <= max_cap * 0.4:
            color = '#B3EE3A'
        elif number <= max_cap * 0.6:
            color = '#EEC900'
        elif number <= max_cap * 0.8:
            color = '#EE7600'
        else:
            color = '#EE4000'
        ax.plot(X, Y, color=color)
    plt.savefig(filename, bbox_inches="tight")
    plt.close(fig)


def analyses(edges, capacity):
    for t in range(21600, 45000, 300):
        simultaneous = {}
        for key, value in capacity.items():
            st = [0, 0, 0]
            if t in value:
                st = value[t]
            simultaneous.setdefault(key, st)
        filename = "../../data/1117/fig/{0}.png".format(t)
        plot_road_capacity(edges, simultaneous, filename)


def main():
    # edges = load_edges("../../data/hangzhou.net.xml")
    # load_period_speed("../../data/1025/10221507-10252113.period.txt", edges)
    # load_period_speed("../../data/1030/10302243.period.txt", edges)
    net_file = "../../data/1117/hangzhou_china_joined_fixed_conn.net.xml"
    period_txt = "../../data/1117/1113-1727-c.period.txt"
    edges = load_edges(net_file)
    # load_period_speed(period_txt, edges)
    road_csv = "../../data/1117/1113-1727-1117.road.csv"
    capacity = load_capacity(road_csv)
    analyses(edges, capacity)

if __name__ == '__main__':
    main()
